package com.crayon2f.test.pdf;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ArtCatalogPdfGenerator {

    //    private static final String BASE_DIR = "/Users/crayon2f/Downloads/";
    private static final String BASE_DIR = "D:\\download\\file\\pdf_export\\";

    public static class Artwork {
        String artistName;
        String artworkTitle;
        String size;
        String material;
        String year;
        String price;
        String imagePath;

        public Artwork(String artistName, String artworkTitle, String size,
                       String material, String year, String price, String imagePath) {
            this.artistName = artistName;
            this.artworkTitle = artworkTitle;
            this.size = size;
            this.material = material;
            this.year = year;
            this.price = price;
            this.imagePath = imagePath;
        }
    }

    public void generateCatalog(String outputPath, List<Artwork> artworks) throws IOException {
        try (PDDocument document = new PDDocument()) {
            // 1. 加载中文字体（必须提供.ttf字体文件）
            PDType0Font chineseFontBold = PDType0Font.load(document, new File(BASE_DIR + "/PF.ttf")); // 微软雅黑粗体
            PDType0Font chineseFontNormal = PDType0Font.load(document, new File(BASE_DIR + "/PF.ttf")); // 微软雅黑常规

            // 2. 添加封面页
            addFixedFullImage(document, BASE_DIR + "header.png");
//            addCoverPage(document, chineseFontBold, chineseFontNormal);

            // 3. 添加作品页
            for (Artwork artwork : artworks) {
                addArtworkPage(document, artwork, chineseFontBold, chineseFontNormal);
            }

            // 4. 添加结束页
            addFixedFullImage(document, BASE_DIR + "footer.png");
//            addClosingPage(document, chineseFontBold, chineseFontNormal);
            PdfHeaderUtil.addPerfectHeader(document, BASE_DIR + "watermark.jpg");
            addIndex(document, artworks);
            document.save(outputPath);
        }
    }

    private void addIndex(PDDocument document, List<Artwork> list) {

        PDDocumentOutline outline = new PDDocumentOutline();
        document.getDocumentCatalog().setDocumentOutline(outline);

        int pages = document.getNumberOfPages();
        for (int i = 0; i < pages; i++) {
            if (i == 0) {
                PDOutlineItem header = new PDOutlineItem();
                header.setTitle("首页");
                setBookmarkDestination(header, document, 0);
                outline.addLast(header);
            } else if (i == pages - 1) {
                PDOutlineItem header = new PDOutlineItem();
                header.setTitle("尾页");
                setBookmarkDestination(header, document, pages - 1);
                outline.addLast(header);
            } else {
                Artwork artwork = list.get(i - 1);
                PDOutlineItem header = new PDOutlineItem();
                header.setTitle(String.format("%s-%s", artwork.artworkTitle, artwork.artistName));
                setBookmarkDestination(header, document, i);
                outline.addLast(header);
            }
        }
    }

    private static void setBookmarkDestination(PDOutlineItem item, PDDocument doc, int pageIndex) {
        PDPageDestination dest = new PDPageFitWidthDestination();
        dest.setPage(doc.getPage(pageIndex));
        item.setDestination(dest);
    }

    private void addFixedFullImage(PDDocument document, String imagePath) throws IOException {
        PDPage page = new PDPage(new PDRectangle(19.05f * 28.35f, 25.4f * 28.35f));
        document.addPage(page);
        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            PDImageXObject image = PDImageXObject.createFromFile(imagePath, document);
            // 获取页面和图片尺寸
            PDRectangle pageSize = page.getMediaBox();
            float pageWidth = pageSize.getWidth();
            float pageHeight = pageSize.getHeight();
            float imageWidth = image.getWidth();
            float imageHeight = image.getHeight();

            // 计算缩放比例(保持宽高比)
            float scale = Math.min(
                    pageWidth / imageWidth,
                    pageHeight / imageHeight
            );

            // 计算缩放后的尺寸
            float scaledWidth = imageWidth * scale;
            float scaledHeight = imageHeight * scale;
//
//            // 计算居中位置
//            float x = (pageWidth - scaledWidth) / 2;
//            float y = (pageHeight - scaledHeight) / 2;

            // 绘制图片
            contentStream.drawImage(image, 0, 0, scaledWidth, scaledHeight);
        }
    }

    private void addArtworkPage(PDDocument document, Artwork artwork,
                                PDType0Font fontBold, PDType0Font fontNormal) throws IOException {
        PDPage page = new PDPage(new PDRectangle(19.05f * 28.35f, 25.4f * 28.35f));
        document.addPage(page);

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            // 设置背景色（白色）
            contentStream.setNonStrokingColor(1f, 1f, 1f);
            contentStream.addRect(0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
            contentStream.fill();

            float margin = 50;

            // 1. 计算文字的精确宽度（关键修正点）
            float textWidth = fontBold.getStringWidth(artwork.price) / 1000f * 14; // 转换为实际宽度
            float textHeight = 14f; // 文字高度
            float paddingX = 6f; // 水平边距
            float paddingY = 3f; // 垂直边距

            // 2. 背景矩形的位置和尺寸
            float rectX = page.getMediaBox().getWidth() - margin - 440 - paddingX;
            float rectY = page.getMediaBox().getHeight() - margin - 8 - textHeight - paddingY;
            float rectWidth = textWidth + 2 * paddingX;
            float rectHeight = textHeight + 2 * paddingY;

            // 3. 绘制背景（RGB: 247,191,199）
            contentStream.setNonStrokingColor(25f / 255f, 1.0f, 90f / 255f);
            contentStream.addRect(rectX, rectY, rectWidth, rectHeight);
            contentStream.fill();

            // 4. 绘制文字（黑色）
            contentStream.setNonStrokingColor(0f, 0f, 0f);
            contentStream.setFont(fontBold, 14);
            contentStream.beginText();
            contentStream.newLineAtOffset(
                    page.getMediaBox().getWidth() - margin - 440,
                    page.getMediaBox().getHeight() - margin - 20
            );
            contentStream.showText(artwork.price);

            System.out.printf("文字宽度: %.2f, 背景宽度: %.2f%n", textWidth, rectWidth);
            System.out.printf("文字位置: (%.2f, %.2f), 背景位置: (%.2f, %.2f)%n",
                    page.getMediaBox().getWidth() - margin - 440,
                    page.getMediaBox().getHeight() - margin - 20,
                    rectX, rectY);
            contentStream.endText();

            // 添加艺术家姓名
            drawCenteredText(contentStream, page, artwork.artistName, 110, fontBold, 20);

            // 添加作品标题
            drawCenteredText(contentStream, page, artwork.artworkTitle, 80, fontBold, 20);

            // 添加作品信息
            String info = String.format("%s / %s / %s", artwork.size, artwork.material, artwork.year);
            drawCenteredText(contentStream, page, info, 50, fontNormal, 16);

            // 添加作品图片
            if (artwork.imagePath != null && !artwork.imagePath.isEmpty()) {
                try {
                    PDImageXObject image = PDImageXObject.createFromFileByExtension(new File(artwork.imagePath), document);
                    // 获取页面和图片尺寸
                    PDRectangle pageSize = page.getMediaBox();
                    float pageWidth = pageSize.getWidth();
                    float pageHeight = pageSize.getHeight();
                    float imageWidth = image.getWidth();
                    float imageHeight = image.getHeight();

                    // 计算缩放比例(保持宽高比)
                    float scale = Math.min(
                            (pageWidth - 50) / imageWidth,   // 左右留10pt边距
                            (pageHeight - 50) / imageHeight  // 上下留10pt边距
                    );

                    // 计算缩放后的尺寸
                    float scaledWidth = imageWidth * scale;
                    float scaledHeight = imageHeight * scale;

                    // 计算居中位置
                    float x = (pageWidth - scaledWidth) / 2;
                    float y = (pageHeight - scaledHeight) / 2;

                    // 绘制图片
                    contentStream.drawImage(image, x, y, scaledWidth, scaledHeight);
                } catch (IOException e) {
                    System.err.println("图片加载失败: " + artwork.imagePath);
                }
            }
        }
    }

    private void drawCenteredText(PDPageContentStream contentStream, PDPage page,
                                  String text, float y, PDType0Font font, float fontSize) throws IOException {
        float titleWidth = font.getStringWidth(text) / 1000 * fontSize;
        float centerX = (page.getMediaBox().getWidth() - titleWidth) / 2;

        contentStream.setFont(font, fontSize);
        contentStream.beginText();
        contentStream.newLineAtOffset(centerX, y);
        contentStream.showText(text);
        contentStream.endText();
    }

    public static void main(String[] args) throws IOException {
        // 初始化作品列表
        List<Artwork> artworks = new ArrayList<>();
        artworks.add(new Artwork("付斌", "《彼时此地No.16》", "60×60cm", "木板综合材料", "2022", "40000", BASE_DIR + "1.jpg"));
        artworks.add(new Artwork("郝世明", "《解释202303》", "115×78cm", "纸本丙烯", "2023", "60000", BASE_DIR + "2.jpg"));
        artworks.add(new Artwork("黄靖杰", "《西湖No.2》", "90×130cm", "绢本设色", "2023", "80000", BASE_DIR + "3.jpg"));
        artworks.add(new Artwork("李昂", "《神思——庐》", "68×50cm", "绢本重彩", "2021", "38000", BASE_DIR + "4.jpg"));

        ArtCatalogPdfGenerator generator = new ArtCatalogPdfGenerator();
        generator.generateCatalog(BASE_DIR + "青年艺术季作品集.pdf", artworks);
        System.out.println("PDF生成成功！");

    }
}